/**
 * Created by zhangguoyu on 16/5/10.
 */

var StatSet = require('./stats/StatSet');
var moment = require('moment');

var CoreData = function () {
  this._global = new StatSet();
  this._days = [];
};

CoreData.prototype.globalStat = function () {
  return this._global;
};

CoreData.prototype.dayStat = function (date) {
  var i = this._days.length;
  var tag = undefined;
  while (i--) {
    if (this._days[i].date === date) {
      tag = this._days[i];
      break;
    }
  }
  if (tag === undefined) {
    tag = {
      date: date,
      stat: new StatSet()
    };
    this._days.push(tag);
  }
  return tag.stat;
};

CoreData.prototype.daySize = function () {
  return this._days.length;
};

CoreData.prototype.today = function () {
  var d = undefined;
  if (arguments.length) {
    d = arguments[0];
  }
  if (d === undefined) {
    d = moment().format('YYYY-MM-DD');
  }
  return this.dayStat(d);
};

CoreData.prototype.yesterday = function () {
  var d = undefined;
  if (arguments.length) {
    d = arguments[0];
  }
  if (d === undefined) {
    d = moment().subtract(1, 'd').format('YYYY-MM-DD');
  }
  return this.dayStat(d);
};

CoreData.prototype._nearestRang = function (rang) {
  var res = [];
  if (Array.isArray(rang)) {
    var start = rang[0];
    var end = rang[1];
    var i = this.daySize();
    var flag = false;
    while (i--) {
      if (flag) {
        res.push(this._days[i]);
        continue;
      }
      if (this._days[i].date === start) {
        flag = true;
        res.push(this._days[i]);
        continue;
      }
      if (this._days[i].date === end) {
        res.push(this._days[i]);
        break;
      }
    }
  }
  return res;
};

CoreData.prototype._nearest = function (dayCount) {
  if (dayCount <= 0) {
    return [];
  }

  if (dayCount >= this.daySize()) {
    return this._days;
  }

  var i = this.daySize();
  var end = i - dayCount;
  var res = [];
  while (i--) {
    if (i < end) {
      break;
    }
    res.push(this._days[i]);
  }
  return res;
};

CoreData.prototype._nearestFrom = function (start, count) {
  var res = [];
  var i = this.daySize();
  var flag = false;
  while (i--) {
    if (count === 0) {
      break;
    }
    if (flag) {
      res.push(this._days[i]);
      continue;
    }
    if (this._days[i].date === start) {
      res.push(this._days[i]);
      count--;
      flag = true;
    }
  }
  return res;
};

CoreData.prototype.nearest = function () {
  if (arguments.length) {
    if (Array.isArray(arguments[0])) {
      return this._nearestRang(arguments[0]);
    } else {
      return this._nearest(arguments[0]);
    }
  }
  if (arguments.length > 1) {
    if (typeof arguments[1] === 'string') {
      return this._nearestFrom([arguments[0], arguments[1]]);
    } else {
      return this._nearestFrom(arguments[0], arguments[1]);
    }
  }
  return this._nearest(30);
};

module.exports = new CoreData();
